﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace IGGCore
{
    public class DepthChartParser : BaseParser
    {
        private string m_currentUrl;

        public DepthChart GetDepthChart(string url)
        {
            m_currentUrl = url;
            DepthChart chart = new DepthChart();
            string transContent = "";
            StreamReader reader = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                reader = new StreamReader(request.GetResponse().GetResponseStream());
                transContent = reader.ReadToEnd();
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            transContent = transContent.Substring(transContent.IndexOf("<div id=\"depth_chart\">"));
            chart.LeftFields = GetPlayers(transContent, "lf");
            chart.CenterFields = GetPlayers(transContent, "cf");
            chart.RightFields = GetPlayers(transContent, "rf");
            chart.FirstBases = GetPlayers(transContent, "1b");
            chart.SecondBases = GetPlayers(transContent, "2b");
            chart.ThirdBases = GetPlayers(transContent, "3b");
            chart.Shortstops = GetPlayers(transContent, "ss");
            chart.Catchers = GetPlayers(transContent, "c");
            chart.DesignatedHitters = GetPlayers(transContent, "dh");
            chart.Pitchers = GetPlayers(transContent, "sp");
            chart.Relievers = GetPlayers(transContent, "p");
            chart.DLs = GetPlayers(transContent, "dl");
            if (chart.Relievers != null && chart.Relievers.Length > 0)
            {
                chart.Closer = chart.Relievers[0];
            }
            chart.Notes = GetNotes(transContent);
            
            return chart;
        }

        private Player[] GetPlayers(string content, string pos)
        {
            Player[] players = null;
            string contentraw = content;
            try
            {
                if (content.IndexOf("<div id=\"pos_" + pos.ToUpper() + "\">") < 0)
                {
                    return null;
                }

                content = content.Substring(content.IndexOf("<div id=\"pos_" + pos.ToUpper() + "\">"));
                content = content.Substring(0, content.IndexOf("</ul>"));
                if (content.IndexOf("</li>") < 0)
                {
                    return null;
                }
                string licontent = content.Substring(content.IndexOf("</li>"));
                string imgcontent = content;
                if (content.IndexOf("<img") > -1)
                {
                    imgcontent = content.Substring(content.IndexOf("<img"));
                }

                if (imgcontent.IndexOf("</div>") > 0)
                {
                    imgcontent = imgcontent.Substring(0, imgcontent.IndexOf("</div>"));
                }
                if (imgcontent.IndexOf("alt") > 0)
                {
                    imgcontent = imgcontent.Substring(imgcontent.IndexOf("alt") + 5);
                }

                string[] starterNames = null;
                string starter = null;
                if (pos.ToLower()!="dl")
                {
                    starter = imgcontent.Substring(0, imgcontent.IndexOf("\""));
                    starterNames = starter.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    int i = 0;
                }


                string[] lis = licontent.Substring(licontent.IndexOf("<li>")).Split(new string[] { "<li>" }, StringSplitOptions.RemoveEmptyEntries);

                List<Player> tempPlayers = new List<Player>();
                List<string> names = new List<string>();
                
                int index = 0;
                foreach (string li in lis)
                {
                    Player player = new Player();
                    if (pos.ToLower() == "dl")
                    {
                        string note = li.Substring(li.IndexOf("<span>") + 7);
                        note = note.Substring(0, note.IndexOf("</span>"));
                        player.Report = note;
                    }
                    string name = li.Substring(li.IndexOf("\">") + 2);
                    name = name.Substring(0, name.IndexOf("<"));

                    string[] liNames = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    if (index == 0 && starterNames != null && starterNames.Length > 1)
                    {
                        player.FirstName = starterNames[0];
                        player.LastName = starterNames[1];
                        if (starterNames.Length > 2)
                        {
                            player.LastName += " " + starterNames[2];
                        }
                        if (starterNames.Length > 3)
                        {
                            player.LastName += " " + starterNames[3];
                        }
                    }
                    else
                    {
                        player.FirstName = liNames[0];
                        player.LastName = liNames[1];
                        if (liNames.Length > 2)
                        {
                            player.LastName += " " + liNames[2];
                        }
                        if (liNames.Length > 3)
                        {
                            player.LastName += " " + liNames[3];
                        }
                    }
                    index++;
                    if (names.Contains(player.FullName)==false)
                    {
                        names.Add(player.FullName);
                        tempPlayers.Add(player);
                    }
                }
                players = new Player[tempPlayers.Count];
                for(int i=0; i<tempPlayers.Count; i++)
                {
                    players[i] = tempPlayers[i];
                }
            }
            catch(Exception ex)
            {
                string raw = "URL: " + m_currentUrl + Environment.NewLine;
                raw += "POS: " + pos + Environment.NewLine + Environment.NewLine;
                raw += ex.Message + Environment.NewLine;
                raw += ex.StackTrace + Environment.NewLine + Environment.NewLine;
                raw += contentraw + Environment.NewLine + Environment.NewLine;
                DebugManager.GetInstance().Debug("Depth Chart", raw);
                throw ex;
            }
            return players;
        }

        private List<Player> GetNotes(string content)
        {
            List<Player> notes = new List<Player>();
            string contentraw = content;
            string[] liNames = null;
            try
            {
                if (content.IndexOf("<div id=\"pos_notes\">") < 0 || content.IndexOf("</ul>") < 0)
                {
                    return null;
                }

                content = content.Substring(content.IndexOf("<div id=\"pos_notes\">"));

                content = content.Substring(0, content.IndexOf("</ul>"));
                if (content.IndexOf("</li>") < 0)
                {
                    return null;
                }
                string licontent = content.Substring(content.IndexOf("</li>"));
                string imgcontent = content;
                if (content.IndexOf("<img") > -1)
                {
                    imgcontent = content.Substring(content.IndexOf("<img"));
                }

                if (imgcontent.IndexOf("</div>") > 0)
                {
                    imgcontent = imgcontent.Substring(0, imgcontent.IndexOf("</div>"));
                }
                if (imgcontent.IndexOf("alt") > 0)
                {
                    imgcontent = imgcontent.Substring(imgcontent.IndexOf("alt") + 5);
                }


                string[] lis = licontent.Substring(licontent.IndexOf("<li>")).Split(new string[] { "<li>" }, StringSplitOptions.RemoveEmptyEntries);
                List<Player> tempPlayers = new List<Player>();
                foreach (string li in lis)
                {
                    Player player = new Player();
                    string temp = li.Substring(li.IndexOf("</a>") + 4);
                    temp = temp.Substring(0, temp.IndexOf("<"));
                    player.Report = temp;

                    string name = li.Substring(li.IndexOf("\">") + 2);
                    name = name.Substring(0, name.IndexOf("<"));

                    liNames = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                    player.FirstName = liNames[0];
                    player.LastName = liNames[1].Substring(0, liNames[1].IndexOf(":"));
                    if (liNames.Length > 2)
                    {
                        player.LastName += " " + liNames[2];
                    }
                    if (liNames.Length > 3)
                    {
                        player.LastName += " " + liNames[3];
                    }
                    if (liNames.Length > 4)
                    {
                        player.LastName += " " + liNames[4];
                    }

                    notes.Add(player);
                }
            }
            catch (Exception ex)
            {
                string raw = "URL: " + m_currentUrl + Environment.NewLine;
                raw += "POS: Notes"+ Environment.NewLine + Environment.NewLine;
                raw += ex.Message + Environment.NewLine;
                raw += ex.StackTrace + Environment.NewLine + Environment.NewLine;
                raw += contentraw + Environment.NewLine + Environment.NewLine;
                DebugManager.GetInstance().Debug("Depth Chart", raw);
                //throw ex;
            }
            return notes;
        }
    }
}
